import time
import json
from datetime import datetime
from sp_api.api import Products
from sp_api.base import Marketplaces, Credentials
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from app.intereface_amazon.databasemodel import AmazonProduct, Base
from app.intereface_amazon.amazon_config import SP_API_CREDENTIALS, MARKETPLACE_CONFIG, DB_CONFIG

class AmazonProductUpdater:
    def __init__(self, marketplace_id='ATVPDKIKX0DER', db_url=None):
        """
        初始化亚马逊产品更新器
        
        参数:
            marketplace_id: 市场ID，默认为美国市场
            db_url: 数据库连接URL
        """
        self.marketplace_id = marketplace_id
        self.marketplace = Marketplaces.US  # 默认使用美国市场
        
        # 设置认证信息
        self.credentials = Credentials(
            refresh_token=SP_API_CREDENTIALS['refresh_token'],
            lwa_client_id=SP_API_CREDENTIALS['lwa_client_id'],
            lwa_client_secret=SP_API_CREDENTIALS['lwa_client_secret'],
            aws_access_key=SP_API_CREDENTIALS['aws_access_key'],
            aws_secret_key=SP_API_CREDENTIALS['aws_secret_key'],
            role_arn=SP_API_CREDENTIALS['role_arn']
        )
        
        # 初始化Products API
        self.products_api = Products(
            marketplace=self.marketplace,
            credentials=self.credentials
        )
        
        # 初始化数据库连接
        if db_url:
            self.engine = create_engine(db_url)
        else:
            self.engine = create_engine(DB_CONFIG['url'])
        Base.metadata.create_all(self.engine)
        self.Session = sessionmaker(bind=self.engine)
    
    def update_products(self, product_updates, batch_size=5):
        """
        批量修改亚马逊产品
        
        参数:
            product_updates: 产品更新数据列表，每个元素是一个字典
            batch_size: 每批处理的产品数量，默认为5
        
        返回:
            更新结果列表
        """
        update_results = []
        session = self.Session()
        
        try:
            for i in range(0, len(product_updates), batch_size):
                batch = product_updates[i:i+batch_size]
                
                try:
                    # 准备产品更新数据
                    updates = []
                    for update in batch:
                        # 转换产品数据为API格式
                        api_update = self._convert_to_api_format(update)
                        updates.append(api_update)
                    
                    # 调用Products API更新产品
                    response = self.products_api.patch_product(
                        body={
                            'products': updates
                        }
                    )
                    
                    # 处理响应
                    if response.payload:
                        # 更新数据库
                        for update in batch:
                            try:
                                # 查找产品
                                product = session.query(AmazonProduct).filter_by(sku=update['sku']).first()
                                
                                if product:
                                    # 更新产品
                                    for key, value in update.items():
                                        if key != 'sku':  # 不更新SKU
                                            setattr(product, key, value)
                                    product.updated_at = datetime.now()
                                
                                update_results.append({
                                    'sku': update['sku'],
                                    'status': 'success'
                                })
                                
                            except Exception as e:
                                update_results.append({
                                    'sku': update.get('sku', 'unknown'),
                                    'status': 'error',
                                    'message': str(e)
                                })
                                print(f"更新产品到数据库时出错: {e}")
                                continue
                        
                        # 提交事务
                        session.commit()
                    else:
                        update_results.append({
                            'batch': i // batch_size + 1,
                            'status': 'error',
                            'message': 'No payload in response'
                        })
                    
                    # 添加延迟以避免API限制
                    time.sleep(2)
                    
                except Exception as e:
                    session.rollback()
                    update_results.append({
                        'batch': i // batch_size + 1,
                        'status': 'error',
                        'message': str(e)
                    })
                    print(f"更新产品批次时出错: {e}")
                    continue
                
        finally:
            session.close()
        
        return update_results
    
    def _convert_to_api_format(self, update):
        """
        将产品更新数据转换为API格式
        
        参数:
            update: 产品更新数据字典
        
        返回:
            API格式的产品更新数据
        """
        # 提取属性
        attributes = {}
        
        # 基本属性
        if 'title' in update:
            attributes['title'] = update['title']
        if 'brand' in update:
            attributes['brand'] = update['brand']
        if 'description' in update:
            attributes['description'] = update['description']
        if 'item_type' in update:
            attributes['item_type'] = update['item_type']
        if 'manufacturer' in update:
            attributes['manufacturer'] = update['manufacturer']
        if 'part_number' in update:
            attributes['part_number'] = update['part_number']
        if 'product_tax_code' in update:
            attributes['product_tax_code'] = update['product_tax_code']
        
        # 价格
        if 'standard_price' in update and 'currency' in update:
            attributes['standard_price'] = {
                'amount': float(update['standard_price']),
                'currency': update['currency']
            }
        
        # 要点
        if 'bullet_points' in update:
            if isinstance(update['bullet_points'], str):
                try:
                    bullet_points = json.loads(update['bullet_points'])
                except:
                    bullet_points = [update['bullet_points']]
            else:
                bullet_points = update['bullet_points']
            attributes['bullet_point'] = bullet_points
        
        # 构建API格式的产品更新数据
        api_update = {
            'sku': update['sku'],
            'productType': update.get('product_type', 'PRODUCT'),
            'attributes': attributes
        }
        
        return api_update
    
    def save_results_to_file(self, results, output_file='update_results.json'):
        """
        将更新结果保存到JSON文件
        
        参数:
            results: 更新结果列表
            output_file: 输出文件名
        """
        with open(output_file, 'w', encoding='utf-8') as f:
            json.dump(results, f, indent=4)
        
        print(f"更新结果已保存到 {output_file}")

# 使用示例
if __name__ == "__main__":
    # 数据库连接URL
    db_url = "mysql+pymysql://username:password@localhost:3306/database_name"
    
    # 创建更新器实例
    updater = AmazonProductUpdater(db_url=db_url)
    
    # 示例产品更新数据
    product_updates = [
        {
            'sku': 'TEST-SKU-001',
            'product_type': 'PRODUCT',
            'title': 'Updated Test Product 1',
            'standard_price': 24.99,
            'currency': 'USD'
        }
    ]
    
    # 更新产品
    update_results = updater.update_products(product_updates)
    
    # 保存结果
    updater.save_results_to_file(update_results) 